import json
import re
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views import View
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.ten_auth.models import User, Question,Reply,Article,Recruit
from libs.baidushenhe import tupian
from libs.qiniuyun import upload
from utils.simmiddleware01 import login_required_my
from utils.ten_token import verify_jwt
# 上传头像
class Upload(APIView):
    def post(self, request):
        data = request.data.get('img')
        tu = data.read()
        result = tupian(tu)
        if 'conclusionType' in result and result['conclusionType'] == 1:
            data.seek(0)
            image = upload(data)
            print(image)
            img = image['key']
        else:
            return JsonResponse({"errno": "400", "errmsg": "图片未经过审核"},status=400)
        return JsonResponse({"imgurl": 'http://s7ph6efw7.hn-bkt.clouddn.com/' + str(img)})


# 前端富文本上传图片
class Common(View):
    def post(self, request):
        data = request.Body.get('upload')
        tu = data.read()
        result = tupian(tu)
        if 'conclusionType' in result and result['conclusionType'] == 1:
            data.seek(0)
            image = upload(data)
            print(image)
        pass


# 获取个人详情
class Userimage(APIView):
    @method_decorator(login_required_my, name='get')
    def get(self, request):
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)['user_id']
        user = User.objects.filter(id=user_id).first()
        labela = user.labels.all()
        labels = []
        for i in labela:
            labels.append({"id": i.id, "label_name": i.label_name})
        question = Question.objects.filter(user_id=user_id).all()
        questions = []
        for i in question:
            lab = []
            labs = i.labels.all()
            for j in labs:
                lab.append({"id": j.id, "label_name": j.label_name})
            questions.append(
                {"id": i.id, "createtime": i.createtime, "labels": lab, "reply": i.reply, 'replyname': i.replyname,
                 'replytime': i.replytime,
                 "title": i.title, "unuseful_count": i.unuseful_count, "useful_count": i.useful_count,
                 "visits": i.visits})
        answer_question = Reply.objects.filter(user_id=user_id).all()
        answer_questions = []
        for i in answer_question:
            suba = []
            for j in Reply.objects.filter(parent_id=i.id,type=1).all():
                user = User.objects.get(id = j.user_id)
                suba.append({"id":j.id,"content":j.content,"createtime":j.createtime,"useful_count":j.useful_count,
                             "unuseful_count":j.unuseful_count,"user":{"id":user.id,"username":user.username,"avatar":user.avatar}})
            user = User.objects.get(id = i.user_id)
            answer_questions.append({"id":i.id,"content":i.content,"createtime":i.createtime,"useful_count":i.useful_count,"problem":i.problem_id,
                                     "unuseful_count":i.unuseful_count,'subs':suba,'user': {"id":user.id,"username":user.username,"avatar":user.avatar},'parent':i.parent_id})
        collected_articles = user.collected_articles.all()
        collected_articlesa = []
        for i in collected_articles:
            usera = User.objects.get(id=user_id)
            art = Article.objects.filter(user_id=usera.id).first()
            collected_articlesa.append({"id":i.id,"title":i.title,"content":i.content,"createtime":i.createtime,
                                        "user":{"id":usera.id,"username":usera.username,"avatar":usera.avatar,"articles":{"id":art.id,"title":art.title}},
                                        'collected_users': [i.id for i in art.collected_users.all()],
                                        "image":usera.avatar})
        enterpises = user.enterpises.all()
        enterpisesa = []
        for i in enterpises:
            recruitsa = []
            for j in Recruit.objects.filter(enterprise_id=i.id).all():
                recruitsa.append({"id":j.id})
            enterpisesa.append({"id":i.id,"name":i.name,"labels":i.labels,"logo":i.logo,"recruits":recruitsa,"summary":i.summary})
        return JsonResponse({"id":user_id,
                             "username": user.username,
                             "mobile": user.mobile,
                             "realname": user.realname,
                             'birthday': user.birthday,
                             "sex": user.sex,
                             "avatar": user.avatar if user.avatar else '',
                             "website": user.website,
                             "email": user.email,
                             "city": user.city,
                             "address": user.address,
                             "labels": labels,
                             'questions': questions,
                             "answer_question":answer_questions,
                             "collected_articles":collected_articlesa,
                             "enterpises":enterpisesa})

    # 修改个人信息
    @method_decorator(login_required_my, name='put')
    def put(self, request):
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)["user_id"]
        user = User.objects.filter(id=user_id).first()
        labela = user.labels.all()
        labels = []
        for i in labela:
            labels.append({"id": i.id, "label_name": i.label_name})
        question = Question.objects.filter(user_id=user_id).all()
        questions = []
        for i in question:
            lab = []
            labs = i.labels.all()
            for j in labs:
                lab.append({"id": j.id, "label_name": j.label_name})
            questions.append(
                {"id": i.id, "createtime": i.createtime, "labels": lab, "reply": i.reply, 'replyname': i.replyname,
                 'replytime': i.replytime,
                 "title": i.title, "unuseful_count": i.unuseful_count, "useful_count": i.useful_count,
                 "visits": i.visits})
        answer_question = Reply.objects.filter(user_id=user_id).all()
        answer_questions = []
        for i in answer_question:
            suba = []
            for j in Reply.objects.filter(parent_id=i.id, type=1).all():
                user = User.objects.get(id=j.user_id)
                suba.append(
                    {"id": j.id, "content": j.content, "createtime": j.createtime, "useful_count": j.useful_count,
                     "unuseful_count": j.unuseful_count,
                     "user": {"id": user.id, "username": user.username, "avatar": user.avatar}})
            user = User.objects.get(id=i.user_id)
            answer_questions.append(
                {"id": i.id, "content": i.content, "createtime": i.createtime, "useful_count": i.useful_count,
                 "problem": i.problem_id,
                 "unuseful_count": i.unuseful_count, 'subs': suba,
                 'user': {"id": user.id, "username": user.username, "avatar": user.avatar}, 'parent': i.parent_id})
        collected_articles = user.collected_articles.all()
        collected_articlesa = []
        for i in collected_articles:
            usera = User.objects.get(id=user_id)
            art = Article.objects.filter(user_id=usera.id).first()
            collected_articlesa.append({"id": i.id, "title": i.title, "content": i.content, "createtime": i.createtime,
                                        "user": {"id": usera.id, "username": usera.username, "avatar": usera.avatar,
                                                 "articles": {"id": art.id, "title": art.title}},
                                        'collected_users': [i.id for i in art.collected_users.all()],
                                        "image": usera.avatar})
        enterpises = user.enterpises.all()
        enterpisesa = []
        for i in enterpises:
            recruitsa = []
            for j in Recruit.objects.filter(enterprise_id=i.id).all():
                recruitsa.append({"id": j.id})
            enterpisesa.append({"id": i.id, "name": i.name, "labels": i.labels, "logo": i.logo, "recruits": recruitsa,
                                "summary": i.summary})
        data = request.data
        user.realname = data.get('realname')
        user.sex = data.get('sex')
        if not re.match(r'^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$', data.get('birthday')):
            return JsonResponse({"success": True,'message': '生日格式错误'})
        else:
            user.birthday = data.get('birthday')
        user.website = data.get('website')
        if not re.match(r'^(http|https)://[^ "]+$', user.website):
            return JsonResponse({"success": True,'message': '网址格式错误'})
        user.email = data.get('email')
        if not re.match(r'^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+$', user.email):
            return JsonResponse({"success": True,'message': '邮箱格式错误'})
        user.city = data.get('city')
        user.address = data.get('address')
        user.avatar = data.get('avatar')
        if user.mobile == data.get('mobile'):
            pass
        else:
            user2 = User.objects.filter(mobile = data.get('mobile')).first()
            if user2:
                return JsonResponse({"success": True,'message': '手机号码已存在'})
            else:
                user.mobile = data.get('mobile')
        if not re.match(r'^1[3-9]\d{9}$', data.get('mobile')):
            return JsonResponse({"success": True,'message': '手机号码格式错误'})
        user.save()
        return Response({"id": user_id, "username": user.username, "mobile": user.mobile, "realname": user.realname,
                         'birthday': user.birthday,
                         "sex": user.sex, "avatar": user.avatar if user.avatar else '',
                         "website": user.website, "email": user.email, "city": user.city,
                         "address": user.address, "labels": labels, 'questions': questions,
                         "answer_question": answer_questions,
                         "collected_articles": collected_articlesa,
                         "enterpises": enterpisesa
                         })


# 修改密码
class SetPassword(View):
    @method_decorator(login_required_my, name='put')
    def put(self, request):
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)["user_id"]
        user = User.objects.filter(id=user_id).first()
        data = json.loads(request.body)
        password = data.get('password')
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({"success": True,'message': '密码格式错误'})
        user.set_password(password)
        user.save()
        return JsonResponse({"errno": "0", "errmsg": "密码修改成功"})


# 关注用户
class Like(View):

    def post(self, request, id):
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)["user_id"]
        user = User.objects.filter(id=user_id).first()
        user.fans.add(id)
        user.save()
        return JsonResponse({"success": True, "message": "关注成功"})

    # 取消关注
    def delete(self, request, id):
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)["user_id"]
        user = User.objects.filter(id=user_id).first()
        user.fans.remove(id)
        user.save()
        return JsonResponse({"success": True, "message": "取消关注成功"})